/**
 * 
 */
package com.dangdang.serviceImpl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.dangdang.domain.User;
import com.dangdang.service.UserService;
import com.dangdang.util.HbnUtils;

/**
 * 用户管理类
 * 
 * @author Wangpeihu
 * @team [Never give up]
 * @since JDK1.6(建议)
 * @date 2010-1-18
 */
public class UserServiceImpl implements UserService {

	/**
	 * 添加一个新用户
	 */
	@Override
	public User addUser(User user) {
		Session s = HbnUtils.getSession();
		try {
			s.beginTransaction();
			s.save(user);
			s.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			s.getTransaction().rollback();
		}
		s.close();
		return user;
	}

	/**
	 * 根据用户ID删除一个用户
	 */
	@Override
	public void deleteUserById(Integer userId) {
		Session s = HbnUtils.getSession();
		try {
			s.beginTransaction();
			s.delete(userId);
			s.getTransaction().commit();
		} catch (Exception e) {
			s.getTransaction().rollback();
			e.printStackTrace();
		} finally {
			s.close();
		}

	}

	/**
	 * 获得所有的用户
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<User> findAllUser() {
		Session session = HbnUtils.getSession();
		Query query = session.createQuery("from User");
		List<User> usertList = query.list();
		session.close();
		return usertList;
	}

	/**
	 * 根据用户邮箱和密码查找的用户<br>
	 * 用于用户登录时检测用户是否存在。
	 */
	@Override
	public User userVerify(String nickName, String password) {
		Session session = HbnUtils.getSession();
		String hql = "from User where nickName=? and password= ?";
		System.out.println(hql);
		Query query = session.createQuery(hql);
		query.setParameter(0, nickName.trim());
		query.setParameter(1, password.trim());
		User user = (User) query.uniqueResult();
		session.close();
		return user;
	}

	/**
	 * 更新一个用户信息
	 */
	@Override
	public void updateUser(User user) {
		Session s = HbnUtils.getSession();
		try {
			s.beginTransaction();
			s.update(user);
			s.getTransaction().commit();
		} catch (Exception e) {
			s.getTransaction().rollback();
			e.printStackTrace();
		} finally {
			s.close();
		}
	}

}
